package com.advert.presentation.converter;

import com.advert.presentation.util.localization.LabelsMap;
import org.jboss.seam.contexts.Contexts;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;

public abstract class ConverterBase implements javax.faces.convert.Converter {
    private final String INVALID_CSS = "invalidInput";

    protected abstract Object convertToObject(FacesContext facesContext, UIComponent uiComponent, String s);

    protected abstract String convertToString(FacesContext facesContext, UIComponent uiComponent, Object o);

    protected FacesMessage buildConversionErrorMessage(String constant) {
        String message = getLabelsMap().get(constant);
        return new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null);
    }


    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        Object retVal = null;
        if (s != null && !s.isEmpty()) {
            try {
                retVal = convertToObject(facesContext, uiComponent, s);
            } catch (ConverterException e) {
                decorateAsInvalid(uiComponent);
                throw e;
            }
        }
        undecorateAsValid(uiComponent);
        return retVal;
    }

    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        String retVal = "";
        if (o != null) {
            retVal = convertToString(facesContext, uiComponent, o);
        }
        return retVal;
    }

    private void decorateAsInvalid(UIComponent uiComponent) {
        if (uiComponent instanceof HtmlInputText) {
            HtmlInputText htmlInputText = (HtmlInputText)uiComponent;
            if (htmlInputText.getStyleClass() == null) {
                htmlInputText.setStyleClass(INVALID_CSS);
            } else if (!htmlInputText.getStyleClass().contains(INVALID_CSS)) {
                htmlInputText.setStyleClass(htmlInputText.getStyleClass() + " " + INVALID_CSS);
            }
        }
    }

    private void undecorateAsValid(UIComponent uiComponent) {
        if (uiComponent instanceof HtmlInputText) {
            HtmlInputText htmlInputText = (HtmlInputText)uiComponent;
            if (htmlInputText.getStyleClass() != null) {
                htmlInputText.setStyleClass(htmlInputText.getStyleClass().replaceAll(INVALID_CSS, ""));
            }
        }
    }

    private LabelsMap getLabelsMap() {
        return (LabelsMap) Contexts.lookupInStatefulContexts("labels");
    }
}
